/** @jsxRuntime classic */
import microApp from '@micro-zoe/micro-app';
import React, {
  forwardRef,
  useCallback,
  useImperativeHandle,
  useRef,
  useState,
} from 'react';
import type { EnhancedMicroAppProps, MicroAppRef } from '../../types';
import MaskLoading from '../Loading/MaskLoading';
// 类型定义已合并到 types/index.ts 中

/**
 * 增强微应用组件
 *
 * 功能特性：
 * - 继承 BasicMicroApp 的所有功能
 * - 集成 MaskLoading 遮罩加载
 * - 支持跨平台优化（PC和移动端）
 * - 提供触摸事件支持
 * - 支持自定义加载渲染
 * - 提供调试信息
 */
const EnhancedMicroApp = forwardRef<MicroAppRef, EnhancedMicroAppProps>(
  (
    {
      // 基础属性
      name,
      url,
      defaultPage,
      routerMode = 'pure',
      keepAlive = false,

      // 移动端增强属性
      showMask = true,
      maskLoading = true,
      loadingText = '加载中...',
      loadingIcon,
      touchEnabled = true,
      onTouchStart,
      onTouchEnd,
      customLoadingRenderer,
      lifeCycleEvents = {},

      // 样式属性
      className,
      style,

      // 其他属性
      ...props
    },
    ref,
  ) => {
    // 状态管理
    const [isLoading, setIsLoading] = useState(true);
    const [loadingError, setLoadingError] = useState<any>(null);

    // 引用
    const containerRef = useRef<HTMLDivElement>(null);
    const microAppRef = useRef<any>(null);

    // 生命周期处理函数
    const handleCreated = useCallback(() => {
      console.log('微应用已创建');
      if (lifeCycleEvents.onCreated) lifeCycleEvents.onCreated();
    }, [lifeCycleEvents]);

    const handleBeforemount = useCallback(() => {
      console.log('微应用即将挂载');
      setIsLoading(true);
      setLoadingError(null);
      if (lifeCycleEvents.onBeforemount) lifeCycleEvents.onBeforemount();
    }, [lifeCycleEvents]);

    const handleMounted = useCallback(() => {
      console.log('微应用已挂载');
      setIsLoading(false);
      if (lifeCycleEvents.onMounted) lifeCycleEvents.onMounted();
    }, [lifeCycleEvents]);

    const handleUnmount = useCallback(() => {
      console.log('微应用已卸载');
      setIsLoading(true);
      if (lifeCycleEvents.onUnmount) lifeCycleEvents.onUnmount();
    }, [lifeCycleEvents]);

    const handleError = useCallback(
      (error: any) => {
        console.error('微应用加载错误:', error);
        setLoadingError(error);
        setIsLoading(false);
        if (lifeCycleEvents.onError) lifeCycleEvents.onError(error);
      },
      [lifeCycleEvents],
    );

    const handleAfterhidden = useCallback(() => {
      console.log('已推入后台');
      if (lifeCycleEvents.onAfterhidden) lifeCycleEvents.onAfterhidden();
    }, [lifeCycleEvents]);

    const handleAftershown = useCallback(() => {
      console.log('已推入前台');
      if (lifeCycleEvents.onAftershown) lifeCycleEvents.onAftershown();
    }, [lifeCycleEvents]);

    // 触摸事件处理
    const handleTouchStartEvent = useCallback(
      (event: React.TouchEvent) => {
        if (touchEnabled && onTouchStart) {
          onTouchStart(event.nativeEvent);
        }
      },
      [touchEnabled, onTouchStart],
    );

    const handleTouchEndEvent = useCallback(
      (event: React.TouchEvent) => {
        if (touchEnabled && onTouchEnd) {
          onTouchEnd(event.nativeEvent);
        }
      },
      [touchEnabled, onTouchEnd],
    );

    // 暴露给父组件的方法
    useImperativeHandle(ref, () => ({
      setLoading: (loading: boolean) => {
        setIsLoading(loading);
      },
      reload: () => {
        console.log('重新加载微应用:', name);
        setIsLoading(true);
        setLoadingError(null);
        if (microAppRef.current) {
          // 使用 micro-app 的 reload 方法
          microApp.reload(name, true);
        } else {
          console.warn('微应用引用不存在，无法重新加载');
        }
      },
      getDebugInfo: () => ({
        isLoading,
        loadingError,
        containerSize: containerRef.current
          ? {
              width: containerRef.current.offsetWidth,
              height: containerRef.current.offsetHeight,
            }
          : null,
      }),
    }));

    // 组件样式
    const containerStyle: React.CSSProperties = {
      position: 'relative',
      height: '100%',
      width: '100%',
      minHeight: '200px', // 确保有最小高度
      overflow: 'hidden',
      ...style,
    };

    const microAppStyle: React.CSSProperties = {
      height: '100%',
      width: '100%',
      display: 'block',
    };

    // 渲染自定义加载器
    const renderCustomLoading = () => {
      if (!customLoadingRenderer) return null;

      return customLoadingRenderer(
        <div />, // 默认loading内容由MaskLoading内部提供
        { showMask, maskLoading },
        isLoading,
      );
    };

    return (
      <div
        ref={containerRef}
        className={className}
        style={containerStyle}
        onTouchStart={handleTouchStartEvent}
        onTouchEnd={handleTouchEndEvent}
      >
        <micro-app
          ref={microAppRef}
          name={name}
          url={url}
          router-mode={routerMode}
          default-page={defaultPage}
          keep-alive={keepAlive}
          style={microAppStyle}
          onCreated={handleCreated}
          onBeforemount={handleBeforemount}
          onMounted={handleMounted}
          onAfterhidden={handleAfterhidden}
          onAftershown={handleAftershown}
          onUnmount={handleUnmount}
          onError={handleError}
          {...props}
        />

        {/* 遮罩加载层 */}
        {isLoading && showMask && maskLoading && (
          <MaskLoading
            visible={true}
            loadingText={loadingText}
            loadingIcon={loadingIcon}
          >
            {renderCustomLoading()}
          </MaskLoading>
        )}

        {/* 错误状态显示 */}
        {loadingError && !isLoading && (
          <div
            style={{
              position: 'absolute',
              top: 0,
              left: 0,
              right: 0,
              bottom: 0,
              display: 'flex',
              flexDirection: 'column',
              alignItems: 'center',
              justifyContent: 'center',
              backgroundColor: 'rgba(255, 255, 255, 0.9)',
              zIndex: 1000,
              padding: '20px',
            }}
          >
            <div
              style={{
                fontSize: '16px',
                color: '#ff4d4f',
                marginBottom: '16px',
                textAlign: 'center',
              }}
            >
              应用加载失败
            </div>
            <button
              type="button"
              onClick={() => {
                setLoadingError(null);
                setIsLoading(true);
                microApp.reload(name, true);
              }}
              style={{
                padding: '8px 16px',
                fontSize: '14px',
                backgroundColor: '#1890ff',
                color: '#fff',
                border: 'none',
                borderRadius: '4px',
                cursor: 'pointer',
              }}
            >
              重新加载
            </button>
          </div>
        )}
      </div>
    );
  },
);

EnhancedMicroApp.displayName = 'EnhancedMicroApp';

export default EnhancedMicroApp;
